<template>
  <div class="kva-container">
    <div class="kva-contentbox">
      <home-page-header>
        <div class="kva-form-search">
          <el-form class="search-form" :inline="true" :model="queryParams" ref="searchForm">
            <el-form-item>
              <el-button type="primary" icon="Plus" @click="handleAdd">添加用户</el-button>
            </el-form-item>
            <el-form-item label="关键词：" prop="keyword">
              <el-input v-model="queryParams.keyword" placeholder="请输入用户名称..." maxlength="100" clearable />
            </el-form-item>
            <el-form-item label="启用状态" prop="status">
              <el-select v-model="queryParams.status" class="m-2" placeholder="请选择启用状态" clearable>
                <el-option
                  v-for="item in [{value:1,label:'启用中'},{value:0,label:'禁止中'}]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click.prevent="handleSearch">搜索</el-button>
              <el-button type="danger" icon="Refresh" @click.prevent="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table v-loading="tableLoading" :data="tableData" stripe border :height="settings.tableHeight()">
          <el-table-column fixed :label="'总数：' + total" width="150" align="center">
            <template v-slot='scope'>
              <span>{{scope.$index+1}}</span>
            </template>
          </el-table-column>
          <el-table-column  fixed label="用户编号" prop="id" width="100" align="center"/>
          <el-table-column fixed label="头像" prop="avatar"  align="center" width="80">
            <template #default="{row}">
              <el-avatar size="small" :src="row.avatar"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column fixed label="用户名" prop="username" width="200" align="center"/>
          <el-table-column  label="账号" prop="account"  width="200" align="center"/>
          <el-table-column label="是否启用" width="200" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.status" 
               @change="handleStatus(scope.row)"
               :active-value="1"
               active-text="启用中"
               inactive-text="已禁止"
               :inactive-value="0">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="授予角色" align="center" width="400">
            <template #default="{row,$index}">
              <el-cascader
                  style="width: 100%;"
                  v-model="row.roleIds"
                  :options="roleList"
                  @change="handleChangeRole(row)"
                  :props="props"
              />
            </template>
          </el-table-column>
          <el-table-column label="老师信息" width="200" align="center">
            <template #default="scope">
              <div>{{ scope.row.teacherId > 0 ?'已绑定':'未绑定' }}</div>

              <el-button v-if="scope.row.teacherId > 0" type="danger" @click="handleUnbind(scope.row.id)">解绑</el-button>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="200" align="center">
            <template #default="scope">
              <span>{{ formatTimeToStr(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" width="200" align="center">
            <template #default="scope">
              <span>{{ formatTimeToStr(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" width="420">
            <template #default="scope">
              <el-button icon="edit" type="info" size="small" @click.stop="handleBindSystem(scope.row)">绑定系统</el-button>
              <el-button icon="edit" type="success" size="small" @click.stop="handleBindTeacher(scope.row)">绑定老师</el-button>
              <el-button icon="edit" type="primary" size="small" @click.stop="handleEdit(scope.row)">编辑</el-button>
              <el-button icon="edit" type="warning" size="small" @click.stop="handleUpdatePwd(scope.row)">重置密码</el-button>
              <el-button icon="remove" type="danger" size="small" @click.stop="handleDel(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="kva-pagination-box center">
          <el-pagination :current-page="queryParams.pageNo" :page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </home-page-header>
    </div>
    <add-users ref="addRef" @load="handleSearch"></add-users>
    <kva-select-authors  ref="selectAuthorRef" @select="handleSelectAuthor"></kva-select-authors>
    <bind-system ref="bindSystemRef"></bind-system>
  </div>
</template>
<script  setup>
import settings from '@/settings'
import KVA from '@/utils/kva.js'
import { formatTimeToStr } from '@/utils/date.js'
import AddUsers from './components/AddUsers.vue'
import BindSystem from "./components/BindSystem.vue";
import {
  findPages,
  unbindByUserId,
  ResetSysUserPassword,
  updateStatus,
  saveUpdate
} from '@/api/sysusers.js'

import {
  findSysRoles,
  saveUserRoles
} from '@/api/sysroles.js'

// 绑定添加
const addRef = ref({})
// 绑定系统
const bindSystemRef = ref({})
// 绑定老师
const selectAuthorRef = ref({})
// 搜索属性定义
const queryParams = reactive({
  pageNo: 1,
  pageSize: 30,
  status:"",
  keyword: ""
})

// 定义响应式得列表数据容器
const tableData = ref([])
const tableLoading = ref(false)
const pages = ref(0)
const total = ref(0)
const searchForm = ref({})


// 加载数据
const handleLodeData = async () => {
  tableLoading.value = true
  const resp = await findPages(queryParams)
  tableLoading.value = false
  tableData.value = resp.data.records.map(c=>{
    c.roleIds = c.roleIds?.split(",")
    return c
  })
  total.value = resp.data.total * 1
  pages.value = resp.data.pages * 1
}

var currentUserId = ref(0)
// 绑定老师
const handleBindTeacher = (row)=>{
  currentUserId.value = row.id
  selectAuthorRef.value.handleOpen(row.teacherId,{teacherFlag:1})
}

// 解绑老师
const handleUnbind = async (userId)=>{
  await unbindByUserId(userId)
  KVA.success("解绑成功!")
  handleLodeData()
}

// 选择老师
const handleSelectAuthor = async (user) => {
  if (currentUserId.value == 0) return;
  var params = {
    id: currentUserId.value,
    teacherId: user.id,
    teacherUsername: user.userName,
    teacherNickname: user.nickName,
    teacherUuid: user.uuid,
    teacherAvatar: user.avatar
  }
  await saveUpdate(params)
  KVA.success("绑定成功!")
  currentUserId.value = 0
  handleLodeData();
}

// 绑定系统
const handleBindSystem = (row)=>{
  bindSystemRef.value.handleOpen(row.id)
}

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  handleLodeData()
}

// 重置
const handleReset = () => {
  searchForm.value.resetFields()
  handleSearch()
}

// 分页size更改
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  handleLodeData()
}

// 分页pageNo更改
const handleCurrentChange = (pno) => {
  queryParams.pageNo = pno
  handleLodeData()
}


// 添加事件
const handleAdd = () => {
  addRef.value.handleOpen()
}

// 编辑
const handleEdit = (row) => {
  addRef.value.handleOpen(row.id)
}

// 删除
const handleDel =  (row) => {
  KVA.confirm("警告", "<strong>您确定要执行此次操作吗？</strong>", { icon: "success" }).then(async() => {
    if(row.roleIds && row.roleIds.length > 0 ){
      KVA.error("存在角色绑定关系,无法删除?")
      return;
    }
    const opid = row.id
    await updateStatus(opid,"isDeleted",1)
    KVA.notifySuccess("删除成功!")
    handleLodeData()
  })
}

// 更新状态
const handleStatus = async (row) => {
   await updateStatus(row.id,"status",row.status)
   KVA.notifySuccess("操作成功!")
}

// 修改密码
const handleUpdatePwd = async (row) => {
  KVA.confirm("警告", "<strong>修改用户默认密码为：123456, 确定要执行此操作吗？</strong>", { icon: "success" }).then(async() => {
    await ResetSysUserPassword(row.id)
    KVA.notifySuccess("更新成功!")
  })
}

const roleList = ref([])
// 查询所有的角色信息
const props = ref({multiple:true,emitPath:false,label:'roleName',value:"id"})
// 角色列表
const handleRoleList = async() => {
   const resp = await findSysRoles()
   roleList.value = resp.data
}


// 授予角色
const handleChangeRole = async (row) => {
  // 获取当前授予的用户
  const params = {
    userId:row.id,
    roleIds:row.roleIds.join(",")
  }
  // 调用授权的接口即可
  await saveUserRoles(params)
  KVA.notifySuccess("用户授予角色成功!")
}


onMounted(() => {
  handleLodeData()
  handleRoleList()
})
</script>


